package logic

import (
	"context"
	"encoding/json"
	"errors"
	"fmt"
	"fresh-go/freshrpc/freshrpc"
	"fresh-go/freshrpc/internal/svc"
	"fresh-go/model/cache"
	"fresh-go/model/mysql"
	"time"

	"github.com/zeromicro/go-zero/core/logx"
)

type FreshShowLogic struct {
	ctx    context.Context
	svcCtx *svc.ServiceContext
	logx.Logger
}

func NewFreshShowLogic(ctx context.Context, svcCtx *svc.ServiceContext) *FreshShowLogic {
	return &FreshShowLogic{
		ctx:    ctx,
		svcCtx: svcCtx,
		Logger: logx.WithContext(ctx),
	}
}

// 生鲜详情方法
func (l *FreshShowLogic) FreshShow(in *freshrpc.FreshShowRequest) (*freshrpc.FreshShowResponse, error) {
	// todo: add your logic here and delete this line

	var fresh mysql.Fresh

	key := fmt.Sprintf("fresh_id_%s", in.FreshId)

	result, _ := cache.Rdb.Get(cache.Ctx, key).Result()

	if result == "" {
		err := fresh.FreshShow(mysql.DB, in.FreshId)
		if err != nil {
			return nil, errors.New("该生鲜不存在")
		}
		marshal, _ := json.Marshal(fresh)
		cache.Rdb.Set(cache.Ctx, key, marshal, time.Minute*30)
	} else {
		json.Unmarshal([]byte(result), &fresh)
	}

	return &freshrpc.FreshShowResponse{
		FreshId:    int64(fresh.ID),
		FreshName:  fresh.FreshName,
		FreshPrice: fresh.FreshPrice,
		FreshNum:   int64(fresh.FreshNum),
		FreshTypes: fresh.FreshTypes,
	}, nil
}
